package com.boot.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse)response;

        String uri = req.getRequestURI();

        List<String> uris = Arrays.asList("/login","/doLogin","/register","/doRegister",".css",".js",".jpg",".jpeg");

        //登录、注册、css、js、图片可以直接访问
        if(uris.contains(uri) || endWith(uri,uris)){
            chain.doFilter(request,response);
        }else{
            //如果已经登录 那么所有都是可以访问的
            String userName = (String) req.getSession().getAttribute("userName");
            if(userName!=null){
                chain.doFilter(request,response);
            }else{ //其他的都是不能直接访问的
                res.sendRedirect("/login");
            }
        }
    }

    public static boolean endWith(String uri,List<String> uris){
        for (String s : uris) {
            if(uri.endsWith(s)){
                return true;
            }
        }
        return false;
    }

}
